<template>
  <div>
    <FormPanel ref="topSearch" :labelWidth="100" :list="topFilterList" :cols="4" :isSubmitBtn="false"></FormPanel>
    <!-- <ButtonArea :containerStyle="{ paddingLeft: '100px' }">
    </ButtonArea> -->
    <FilterTable
      ref="table"
      columnsRef="partPartOutboundStockremovalIndex"
      :columns="columns"
      :fetchapi="fetchapi"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectTableFun"
      :onSyncTableData="syncTableFun"
      :dataSource="dataSource"
    >
      <!-- :isMemoryPagination="true" -->
      <template slot="moreActions">
        <span disabled="isFinished" @click="() => deleteHandle()">删除数据</span>
      </template>
      <template slot="controls" slot-scope>
        <el-button size="small" type="primary" :disabled="buildBtn" @click="newBuild">新建</el-button>
        <el-button size="small" type="primary" :disabled="saveltBtn" @click="saveSales">保存</el-button>
        <el-button size="small" type="primary" :disabled="outStockBtn" @click="outStock">出库</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" :disabled="addbtn" @click="addFun">新增</el-button>
        <!-- <el-button size="small" type="primary" :disabled="batchMovebtn" @click="batchMove">批量移库</el-button> -->
        <!-- <el-button size="small" type="primary" :loading="assignLeisureLoading" :disabled="batchMovebtn" @click="handleAssignLeisurePosition">默认空库位</el-button> -->
        <el-button size="small" type="primary" :disabled="cancelBtn" @click="cancel">取消</el-button>
        <el-button size="small" type="primary" :disabled="deleteSales" @click="cancelOrder">作废</el-button>
        <!-- <el-button size="small" type="primary" :disabled="printlBtn" @click="handlePrint">打印</el-button> -->
        <UploadFile
          style="margin: 0 10px;"
          :initial-value="fileInitalValue"
          isOnlyButton
          :limit="20"
          :disabled="addbtn"
          type="primary"
          icon="el-icon-download"
          :actionUrl="`${server.DMSCLOUD_PART}/basedata/ttSalesPart/importMovePart`"
          @change="handleUploadChange"
          >导入</UploadFile
        >
        <el-button size="small" type="primary" :disabled="addbtn" :loading="exportModelLoading" @click="exportModel">导出模板</el-button>
      </template>
    </FilterTable>
    <!-- 选择移库单号弹窗 -->
    <BaseDialog title="移库查询" :modal="true" :visible.sync="showMoveNo" :destroyOnClose="true" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <queryMoveNo :ptype="this.ptype" :moveNo="moveNo" :salerList="salerList" @close="close"></queryMoveNo>
    </BaseDialog>
    <!-- 新增弹窗 -->
    <Drawer :visible.sync="moveAddVisible" :title="dialogTitle" :destroyOnClose="true" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <moveAdd :rowData="rowsData" :existDataList="dataSource" @changedata="moveAddConfirm" @closeTwo="closeTwo" />
    </Drawer>
    <!-- 批量新增 -->
    <BaseDialog :visible.sync="moveBatchAddVisible" :title="dialogTitle" :destroyOnClose="true" width="20%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <BatchMove :storageItemsList="storageItemsList" @changedata="passValue" @closeThree="closeThree" />
    </BaseDialog>
    <!-- 修改弹窗 -->
    <BaseDialog :visible.sync="moveBatchEditVisible" :title="dialogTitle" :destroyOnClose="true" width="60%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <EditMove :editData="editData" :rowsData="rowsData" @changedata="passValue" @closeFour="closeFour" @delRows="delRows" />
    </BaseDialog>
    <!-- 打印 -->
    <div v-if="dy">
      <BasePrint
        ref="print"
        :data="SalesprintList"
        :printerType="printParams.vPrintType ? (printParams.vPrintType == 99901002 ? 'stylus' : 'laser') : 'stylus'"
        :alwaysPrint="printParams.vPageType ? (printParams.vPageType == 99911002 ? true : false) : true"
        :printCopies="printParams.nPages || 1"
        :direction="printParams.vPageDirection == 99921001 ? 'horizontal' : 'vertical'"
        :directPrint="printParams.vDirectPrint ? (printParams.vDirectPrint == 1 ? true : false) : false"
        :isDuplex="printParams.vBothPrint == 1 ? true : false"
        template="templateStockremoval"
      />
    </div>
  </div>
</template>

<script>
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import queryMoveNo from './queryMoveNo';
import * as Util from '@/utils/index.js';
import moveAdd from './moveAdd';
import BatchMove from './batchMove';
import EditMove from './editMove';
import { jsonToHump } from '@/utils';
import SERVER from '@/api/server';
import { notifyAction, isFormEmpty } from '@/utils';
import { queryUseablePositionListByStorage } from '@/api/part/partInventory/partInventory/index.js';
import { getDealerUser } from '@/api/customerRepair/customerComplaint/customerComplaintReception';
import { save, queryPartInfos, outStorage, cancelMoveOrder, delMoveOrder, queryUsableLocations, queryPrintMoveData } from '@/api/part/partOutbound/stockremoval/index';
import { getStorageList } from '@/api/part/common';
import { dealerPrintApi } from '@/api/repair/index.js';
import { exportMoveModel } from '@/api/part/partOut/partSales/index';
import { exportExcelFile, arrayObjDeWeight } from '@/utils/index';
import { queryUnitCode } from '@/api/repair/batchEventManagement/activityDistribution';

export default {
  name: 'partInformation',
  components: {
    queryMoveNo,
    moveAdd,
    BatchMove,
    EditMove
  },
  mixins: [dictionary],
  data() {
    this.conf = { add: '新增', edit: '编辑', show: '显示' };
    this.editableS = true;
    return {
      SalesprintList: {},
      dy: false,
      topFilterList: this.createTopFilterList(),
      fetchParams: { xhrAbort: true },
      fetchapi: queryPartInfos,
      visible: false,
      dialogTitle: '',
      moveNo: '',
      columns: this.createTableColumns(),
      showMoveNo: false, // 是否显示移库单号框
      moveBatchAddVisible: false,
      moveBatchEditVisible: false,
      handleType: '',
      formData: {},
      dataSource: [],
      fileInitalValue: [],
      buildBtn: false,
      saveltBtn: true,
      outStockBtn: true,
      cancelBtn: true,
      moveAddVisible: false,
      deleteSales: true,
      printlBtn: true, // 原true
      addbtn: true,
      batchMovebtn: true,
      isFinished: false, // 编辑
      editData: {},
      salerList: {}, // 销售列表
      rowsData: [],
      exportModelLoading: false,
      transferNo: '',
      selectRow: null,
      delArr: [],
      assignLeisureLoading: false,
      storagePositionList: {},
      syncTableList: [], // 同步表单数据
      storageItemsList: [], // 仓库列表
      storageList: [],
      server: SERVER,
      printParams: {} // 打印参数
    };
  },
  computed: {
    ptype() {
      return this.$route.meta.ptype;
    } // 模块区分
  },
  created() {
    this.$nextTick(() => {
      this.getSalerList();
    });
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.initStorageList();
    this.getUnit();
    // this.queryPrintParams();
  },
  methods: {
    // 查询仓库列表
    async initStorageList() {
      const res = await getStorageList();
      this.storageItemsList = res.data.map(x => ({
        text: x.STORAGE_NAME,
        value: x.STORAGE_CODE,
        tag: x.OEM_TAG
      }));
      this.columns.find(x => x.dataIndex == 'OLD_STORAGE_CODE').dictItems = this.storageItemsList;
      this.columns.find(x => x.dataIndex == 'NEW_STORAGE_CODE').dictItems = this.storageItemsList;
      // (this.storageList[x.STORAGE_CODE] = x.STORAGE_NAME)
    },
    // 打印的方法
    async handlePrint() {
      // 打印数据
      let res = await queryPrintMoveData(this.topFilterList[0].initialValue);
      this.SalesprintList['transferNo'] = this.topFilterList.find(x => x.fieldName === 'transferNo').initialValue;
      this.SalesprintList['transferDate'] = moment(this.topFilterList.find(x => x.fieldName === 'transferDate').initialValue).format('YYYY-MM-DD');
      if (res.resultCode == 200) {
        this.SalesprintList['items'] = res.data.detailInfo;
        this.dy = true;
        // 打印
        this.$nextTick(() => {
          this.$refs.print.EXCUTE_PRINT();
        });
      }
    },
    close(val) {
      if (val) {
        this.topFilterList[0].initialValue = val[0].transferNo;
        this.topFilterList[1].initialValue = val[0].transferDate;
        this.topFilterList[0].disabled = true;
        let obj = { id: val[0].transferNo };
        this.fetchParams = Object.assign({}, obj, { xhrAbort: false });
        this.isFinished = val[0].isFinished == '10041001' ? true : false;
        if (val[0].isFinished == '10041001') {
          this.saveltBtn = true;
          this.outStockBtn = true;
          this.cancelBtn = false;
          this.addbtn = true;
          this.deleteSales = true;
          this.printlBtn = false;
          this.buildBtn = true;
          this.columns.find(x => x.dataIndex == 'column-action').disabled = true;
        } else {
          this.saveltBtn = false;
          this.outStockBtn = false;
          this.cancelBtn = false;
          this.addbtn = false;
          this.buildBtn = true;
        }
      }
      // // 出库按钮解禁
      // this.outStockBtn = false;
      // // 作废按钮解禁
      // this.deleteSales = false;
      this.showMoveNo = false;
      // this.columns = [...this.columns];
    },
    closeTwo() {
      this.moveAddVisible = false;
    },
    closeThree(val) {
      // console.log(123213);

      if (val) {
        this.dataSource = val;
        this.isFinished = false;
        this.columns = [...this.columns];
        // this.BaseTable.EXECUTE_INSERT(this.dataSource);
      }
      this.moveBatchAddVisible = false;
    },
    // 点击默认空库位(递归赋值操作)
    handleAssignLeisurePosition() {
      if (!this.dataSource.length) {
        Util.notifyAction('请先添加配件明细', 'warning');
        return;
      }
      if (this.assignLeisureLoading) return;
      this.assignLeisureLoading = true;
      this.recursionAssignLeisurePosition(0);
    },
    // 递归赋值空闲库位
    async recursionAssignLeisurePosition(index) {
      if (index > this.dataSource.length - 1) {
        this.assignLeisureLoading = false;
        Util.notifyAction('空闲库位赋值成功', 'success');
      } else {
        let rowData = this.dataSource[index];
        // console.log(rowData, 123213);

        if (rowData.NEW_STORAGE_CODE && rowData.NEW_STORAGEPOSITION_CODE !== 0 && !rowData.NEW_STORAGEPOSITION_CODE) {
          if (this.storagePositionList[rowData.NEW_STORAGE_CODE] && this.storagePositionList[rowData.NEW_STORAGE_CODE].length) {
            // 当库位篮子中有此仓库的值并且此仓库可用库位列表不为空的时候取第一个空库位 赋值给当前行
            if (this.storagePositionList[rowData.NEW_STORAGE_CODE][0] || this.storagePositionList[rowData.NEW_STORAGE_CODE][0] === 0) {
              this.dataSource[index].NEW_STORAGEPOSITION_CODE = this.storagePositionList[rowData.NEW_STORAGE_CODE][0];
              this.storagePositionList[rowData.NEW_STORAGE_CODE].splice(0, 1);
            }
            this.recursionAssignLeisurePosition(index + 1);
          } else {
            // 库位篮子中没有此库位的时候请求库位数据并添加到篮子中
            let storageCode = rowData.NEW_STORAGE_CODE;
            console.log(storageCode);

            let res = await queryUseablePositionListByStorage({
              storageCode
            });
            // 如果没有库位 终止
            if (res.resultCode == 200 && res.data[0].error) {
              this.assignLeisureLoading = false;
              return this.$notify.warning({ title: '提示信息', message: '新仓库中没有库位可以使用' });
            }
            if (res.resultCode == 200 && !res.data[0].error) {
              this.storagePositionList[rowData.NEW_STORAGE_CODE] = res.data.map(item => item.storagePositionCode);
              this.recursionAssignLeisurePosition(index);
            } else {
              this.recursionAssignLeisurePosition(index + 1);
            }
          }
        } else {
          this.recursionAssignLeisurePosition(index + 1);
        }
      }
    },
    closeFour(val) {
      // console.log(123213, val);

      if (val) {
        // let temp2 = this.syncTableList.find(item => item.PART_NO === val.PART_NO);
        for (const temp2 of this.BaseTable.list) {
          // console.log(temp2, val, '编辑带回信息');
          if (temp2._uid == val.uid) {
            temp2.TRANSFER_QUANTITY = val.TRANSFER_QUANTITY;
            temp2.NEW_STORAGEPOSITION_CODE = val.NEW_STORAGEPOSITION_CODE;
            temp2.COST_AMOUNT = temp2.TRANSFER_QUANTITY * temp2.COST_PRICE;
            temp2.NEW_STORAGE_CODE = val.NEW_STORAGE_CODE;
            temp2.NEW_STORAGE_NAME = val.NEW_STORAGE_NAME;
          }
        }

        // this.columns = [...this.columns];
        this.saveltBtn = false;
        this.outStockBtn = true;
        this.$notify.success({ title: '提示信息', message: '编辑成功!' });
      } else {
        console.log('false');
      }
      this.moveBatchEditVisible = false;
    },
    delRows(val) {
      // 删除当前行数据
      console.log('删除', val);
      // console.log(this.syncTableList, 'table的数据');
      this.$confirm('新仓库该配件没有库位可用,是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 删除选中数据到配件移库单和明细
          this.dataSource.splice(val.$index, 1);
          this.columns = [...this.columns];
          this.moveBatchEditVisible = false;
        })
        .catch(() => {});
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '移库单号',
          fieldName: 'transferNo',
          placeholder: '移库单号',
          disabled: false,
          unitRender: props => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={this.openCustomerDealer}></el-button>
              </div>
            );
          },
          onEnter: val => {
            this.openCustomerDealer();
          }
        },
        {
          type: 'DATE',
          label: '移库日期',
          disabled: true,
          fieldName: 'transferDate',
          valueFormat: 'yyyy-MM-dd'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 70,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={this.isFinished} onClick={() => this.editHandle(props.row)}>
                  编辑
                </el-button>
              </div>
            );
          }
        },
        {
          title: '原仓库',
          dataIndex: 'OLD_STORAGE_CODE',
          sorter: true,
          filter: true,
          dictItems: [],
          filterType: 'checkbox'
        },
        {
          title: '原库位代码',
          dataIndex: 'OLD_STORAGEPOSITION_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '新仓库',
          dataIndex: 'NEW_STORAGE_CODE',
          sorter: true,
          filter: true,
          dictItems: [],
          filterType: 'checkbox'
        },
        {
          title: '新库位代码',
          dataIndex: 'NEW_STORAGEPOSITION_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '计量单位',
          dataIndex: 'UNIT_CODE',
          sorter: true,
          dictItems: [],
          filterType: 'checkbox'
        },
        {
          title: '移库数量',
          dataIndex: 'TRANSFER_QUANTITY',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '含税成本单价',
          dataIndex: 'COST_PRICE',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '含税成本金额',
          dataIndex: 'COST_AMOUNT',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number',
          render: val => {
            val.row.COST_AMOUNT = (val.row.COST_PRICE * val.row.TRANSFER_QUANTITY).toFixed(2);
            return <span>{val.row.COST_AMOUNT}</span>;
          }
        }
      ];
    },
    computePrice(val) {
      console.log(val, 232);
    },
    selectTableFun(val) {
      this.selectRow = val;
    },
    exportModel() {
      this.exportModelLoading = true;
      exportMoveModel().then(res => {
        console.log('res:::', res);
        Util.exportExcelFile(res.data, '配件移库模板');
        this.exportModelLoading = false;
      });
    },
    // 配件导入成功事件
    handleUploadChange(e) {
      console.log('e:::', e);
      if (e != 1) {
        // if (this.initReceiver) {
        // console.log('导入文件上传成功', e[e.length - 1].url);
        this.fileInitalValue = e;
        let excelData = _.cloneDeep(e[e.length - 1].url.result);
        // for (const item of this.tableData) {
        //   for (const items of excelData) {
        //     if (item.PART_NO == items.PART_NO && item.STORAGE_CODE == items.STORAGE_CODE) {
        //       item.PART_QUANTITY = Number(item.PART_QUANTITY) + Number(items.PART_QUANTITY);
        //     }
        //   }
        //   excelData = excelData.filter(items => {
        //     return items.PART_NO != item.PART_NO || item.STORAGE_CODE != items.STORAGE_CODE;
        //   });
        // }
        console.log(excelData, 'excelData');
        if (excelData.length) {
          this.formatPartsData(excelData);
        }
        this.handleDetailSelectConfirm(excelData, e[e.length - 1].url.errorList);
        // } else {
        //   this.$notify.error({ title: '提示信息', message: `请选择领料人` });
        // }
      }
    },
    handleDetailSelectConfirm(e, data) {
      let partList = e;
      // 校验重复配件
      let newPartArr = [],
        repeatingPartArr = []; // 重复配件，新配件
      console.log('datasource::', this.dataSource);
      console.log('partList::', partList);
      partList.map(item => {
        if (this.dataSource.find(x => x.PART_NO == item.PART_NO)) {
          repeatingPartArr.push(item);
        } else {
          newPartArr.push(item);
        }
      });
      if (repeatingPartArr.length) {
        let idsArr = repeatingPartArr.map(item => item.PART_NO);
        notifyAction('此订单类型禁止添加重复配件，配件代码：' + idsArr.join(','), 'warning');
      }
      newPartArr = JSON.parse(JSON.stringify(newPartArr)); // 浅拷贝防止原始数据修改
      this.formatPartsData(newPartArr);
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(newPartArr);
      if (data.length > 0) {
        let errorData = data.map(x => {
          console.log(x, 'xxx');
          if (x.result == '查询不到库存或者旧仓库的可用库存不足以移库') {
            return '旧仓库：' + x.oldStorageCode + '中配件：' + x.partNo + '查询不到库存或者旧仓库的可用库存不足以移库';
          } else if (x.result == '新仓库代码错误或新仓库无可用库位') {
            return '新仓库：' + x.newStorageCode + '新仓库代码错误或新仓库无可用库位';
          } else if (x.result == '配件移库数量为负') {
            return '配件：' + x.partNo + '移库数量为负';
          } else if (x.result == '油电件仓库不能相互移库') {
            return '旧仓库：' + x.oldStorageCode + '新仓库：' + x.newStorageCode + ' 油电件仓库不能相互移库';
          } else if (x.result == '原厂库与非原厂库不能相互移库') {
            return '旧仓库：' + x.oldStorageCode + '新仓库：' + x.newStorageCode + ' 原厂库与非原厂库不能相互移库';
          }
        });
        console.log(errorData, 'errorData');
        this.$notify.warning({ title: '提示信息', message: `导入成功，已做去重处理,${errorData.join('，')}，请确认模板` });
      } else {
        notifyAction('配件导入成功，已做去重处理', 'success');
      }
    },
    formatPartsData(list) {
      list.map((item, index) => {
        // 处理采购数量，套餐类型单独处理 incount数量x订购套数
        this.$set(list[index], 'IN_QUANTITY', item.PART_QUANTITY);
        this.$set(list[index], 'IN_AMOUNT', item.PART_COST_PRICE * item.PART_QUANTITY);
        this.$set(list[index], 'IN_PRICE_TAXED', item.PART_COST_PRICE * (1 + this.tax));
        this.$set(list[index], 'IN_AMOUNT_TAXED', item.IN_PRICE_TAXED * item.PART_QUANTITY);
      });
    },
    // 操作列删除按钮
    deleteHandle() {
      console.log(this.selectRow, '选中的数据');
      if (!this.isFinished) {
        this.$confirm('是否确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            // 删除选中数据到配件移库单和明细
            // let result = await delMoveOrder({ transferNo: this.topFilterList[0].initialValue ? this.topFilterList[0].initialValue : '' });
            // 作废成功
            // if (result.resultCode == 200) {
            // console.log(123, this.columns);
            // console.log(this.syncTableList, 'table的数据');
            // console.log(this.syncTableList.splice(val.$index, 1));
            // this.dataSource = this.syncTableList;
            for (const item of this.selectRow) {
              if (item.ITEM_ID) {
                this.delArr.push(item.ITEM_ID);
              }
            }
            this.$refs.table.EXECUTE_DELETE(this.selectRow);
            this.outStockBtn = true;
            return this.$notify.success({ title: '提示信息', message: '删除成功' });
            // }
          })
          .catch(() => {});
        // outStorage;
      } else {
        this.$notify.error({ title: '提示信息', message: '该单号已出库，无法删除配件!' });
      }
    },
    addHandle() {
      this.handleType = 'add';
      this.showHandler();
    },
    // 打开移库单号弹框
    openCustomerDealer() {
      let res = this.$refs.topSearch.SUBMIT_FORM();
      // console.log(11123213, res);
      this.isFinished = false;
      this.moveNo = res.transferNo;
      this.showMoveNo = true;
    },
    // 编辑按钮
    async editHandle(row) {
      this.dialogTitle = `配件移库编辑`;
      console.log('row::', row);
      let res = await queryUsableLocations({ storageCode: row.NEW_STORAGE_CODE, partNo: row.PART_NO });
      if (res.data.find(item => item.error)) {
        this.delRows(row);
      } else {
        this.rowsData = this.syncTableList;
        this.editData = { ...row, data: res.data };
        this.moveBatchEditVisible = true;
      }
    },
    // 点击新建
    newBuild() {
      // this.form[0].disabled = true;
      // this.form[1].disabled = false;
      // this.form[3].disabled = false;
      // this.form[4].disabled = false;
      let date = new Date();
      /* var Y = date.getFullYear() + '-';
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      var D = date.getDate() + ' ';
      let today = Y + M + D;*/
      this.topFilterList[0].disabled = true;
      this.topFilterList[1].disabled = true;
      this.topFilterList[1].initialValue = date;
      this.cancelBtn = false;
      this.addbtn = false;
      this.buildBtn = true;
      this.isFinished = false;
      // 批量
      this.batchMovebtn = false;
      // 保存按鈕解禁
      this.saveltBtn = false;
    },
    // 取消点击
    cancel() {
      this.buildBtn = false;
      this.saveltBtn = true;
      this.batchMovebtn = true;
      this.outStockBtn = true;
      this.cancelBtn = true;
      this.deleteSales = true;
      this.isFinished = false;
      this.printlBtn = true;
      this.addbtn = true;
      this.delArr = [];
      this.storagePositionList = {};
      this.topFilterList[0].disabled = false;
      this.topFilterList[0].initialValue = '';
      this.topFilterList[1].initialValue = '';
      this.BaseTable.EXECUTE_DELETE(this.syncTableList);

      // 清空table
      this.dataSource = [];
      this.columns = [...this.columns];
    },
    // 点击新增
    addFun() {
      this.dialogTitle = `配件移库新增`;
      this.moveAddVisible = true;
      this.batchMovebtn = true;
      this.rowsData = this.syncTableList;
    },
    // 批量移库
    batchMove() {
      this.dialogTitle = `批量移库`;
      this.moveBatchAddVisible = true;
    },
    // 点击保存
    saveSales() {
      for (const item of this.dataSource) {
        if (!item.NEW_STORAGEPOSITION_CODE) {
          return this.$notify.error({ title: '提示信息', message: '请选择新库位' });
        }
      }
      this.dataSource;
      console.log(this.dataSource, 'datasource');

      this.$confirm('是否确认保存?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 保存选中数据到配件移库单和明细;
          var list = [];
          // console.log(111, 11, this.syncTableList);

          if (this.syncTableList.length <= 0) {
            return this.$notify.error({ title: '提示信息', message: '不允许提交空表单' });
          }
          // 提示信息
          // let msg;
          // // 校验同一仓库库位是否被占用
          // let newStorageLocations = [];
          // this.syncTableList.map(x => (newStorageLocations[x.NEW_STORAGEPOSITION_CODE] = x.NEW_STORAGE_CODE));
          // console.log(newStorageLocations, '校验同一仓库库位是否被占用');
          // if (newStorageLocations.length != this.syncTableList.length) {
          //   return this.$notify.warning({ title: '提示信息', message: '请检查新仓库配件库位是否有重复' });
          // }
          let flag = false;
          this.syncTableList.forEach(x => {
            console.log('这是x' + x.STORAGE_CODE + x.NEW_STORAGE_CODE + x.OLD_STORAGEPOSITION_CODE);
            if (x.TRANSFER_QUANTITY <= 0) {
              flag = true;
            }
            let itemList = {
              itemId: x.ITEM_ID,
              costPrice: x.COST_PRICE,
              partNo: x.PART_NO,
              partName: x.PART_NAME,
              unitCode: x.UNIT_CODE,
              oldStorageCode: x.STORAGE_CODE ? x.STORAGE_CODE : x.OLD_STORAGE_CODE,
              newStorageCode: x.NEW_STORAGE_CODE,
              transferDate: x.TRANSFER_DATE,
              transferQuantity: x.TRANSFER_QUANTITY,
              costAmount: x.COST_AMOUNT,
              oldStoragepositionCode: x.STORAGE_POSITION_CODE,
              newStoragepositionCode: x.NEW_STORAGEPOSITION_CODE
            };
            list.push(itemList);
          });
          if (flag) {
            this.$notify.warning({ title: '提示信息', message: '移库数量错误' });
          }
          // console.log('传的参数', list);
          let result = await save({
            transferNo: this.topFilterList[0].initialValue ? this.topFilterList[0].initialValue : '',
            transferSign: '',
            isDeletes: this.delArr,
            partMoveItemTable: list,
            ptype: this.ptype ? this.ptype : null // 模块区分
          });
          // 保存成功
          if (result.resultCode === 200) {
            let transferNo = result.data.transferNo;
            // 单号赋值给当前移库单号文本框
            this.topFilterList[0].initialValue = transferNo;
            this.topFilterList[0].disabled = true;
            this.addbtn = false;
            this.outStockBtn = false;
            this.deleteSales = false;
            this.saveltBtn = false;
            this.batchMovebtn = true;
            // this.dataSource = [];
            this.columns = [...this.columns];
            // return this.$notify.success({ title: '提示信息', message: '保存成功' });
            this.$notify.success({ title: '提示信息', message: '保存成功' });
            // this.fetchParams = { xhrAbort: false, id: transferNo };
            // this.fetchParams = { ...fetchParams };
            // 清空插入日志
            this.clearInsert();
          }
        })
        .catch(() => {});
    },
    // 点击作废
    cancelOrder() {
      if (this.syncTableList.length <= 0) {
        this.$notify.error({ title: '提示信息', message: '不允许提交空表单!' });
      } else {
        console.log(this.syncTableList, 'table的数据');
        this.$confirm('是否确认作废?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            // 保存选中数据到配件移库单和明细
            var list = [];
            this.syncTableList.forEach(x => {
              console.log('这是x' + x.STORAGE_CODE + x.NEW_STORAGE_CODE + x.OLD_STORAGEPOSITION_CODE);
              let itemList = {};
              list.push(itemList);
            });
            let result = await cancelMoveOrder({ transferNo: this.topFilterList[0].initialValue ? this.topFilterList[0].initialValue : '' });
            // 作废成功
            if (result.resultCode == 200) {
              //              this.$refs.table.$refs.pageTable.list = [];
              this.dataSource = [];
              this.columns = [...this.columns];
              this.cancel();
              return this.$notify.success({ title: '提示信息', message: '作废成功' });
            }
            this.isFinished = false;
          })
          .catch(() => {});
        // outStorage;
      }
    },
    // 点击出库
    outStock() {
      // 打印按钮解禁
      this.printlBtn = false;
      if (this.syncTableList.length <= 0) {
        this.$notify.error({ title: '提示信息', message: '不允许提交空表单!' });
      } else {
        console.log(this.syncTableList, 'table的数据');
        this.$confirm('是否确认出库?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            // 保存选中数据到配件移库单和明细
            var list = [];
            this.syncTableList.forEach(x => {
              console.log('这是x' + x.STORAGE_CODE + x.NEW_STORAGE_CODE + x.OLD_STORAGEPOSITION_CODE);
              let itemList = {};
              list.push(itemList);
            });
            let result = await outStorage({ transferNo: this.topFilterList[0].initialValue ? this.topFilterList[0].initialValue : '' });
            // 保存成功
            if (result.resultCode == 200) {
              if (result.data.result == 'error') {
                return this.$notify.error({ title: '提示信息', message: result.data.msg });
              }
              this.buildBtn = true;
              this.saveltBtn = true;
              this.outStockBtn = true;
              this.cancelOrder = true;
              this.printlBtn = false;
              this.isFinished = true;
              this.addbtn = true;
              this.batchMovebtn = true;
              this.deleteSales = true;
              this.topFilterList.find(item => item.fieldName == 'transferNo').disabled = true;
              return this.$notify.success({ title: '提示信息', message: '出库成功' });
            }
          })
          .catch(() => {});
        // outStorage;
      }
    },
    // 清空之前对组件的 CURD 操作记录，没有参数
    clearInsert() {
      this.$refs.table.CLEAR_EXECUTE_LOG();
    },
    // 新建调拨出库单->保存触发
    moveAddConfirm(val) {
      // console.log(this.dataSource, val, 'hexj001');
      let insertRow = JSON.parse(JSON.stringify(val));
      if (this.dataSource.length) {
        if (this.dataSource.find(x => x.PART_NO == insertRow.PART_NO)) {
          return this.$notify.warning({ title: '提示信息', message: '该配件已存在' });
        }
      }
      // this.dataSource.push(val);
      this.$refs.table.EXECUTE_INSERT(insertRow);
      this.outStockBtn = true; // 新增配件后禁用出库按钮
      return this.$notify.success({ title: '提示信息', message: '添加成功！' });
    },
    passValue(obj) {
      console.log(this.syncTableList, 'table的数据');
      if (obj.PART_NO != '' && obj.STORAGE_CODE != '') {
        if (this.syncTableList.length > 0) {
          for (const item of this.syncTableList) {
            if (item.PART_NO == obj.PART_NO && item.STORAGE_CODE == obj.STORAGE_CODE && item.NEW_STORAGE_CODE == obj.NEW_STORAGE_CODE) {
              return this.$notify.error({ title: '提示信息', message: '信息已存在，不允许重复添加!' });
            }
          }
        }
      }
      // 给折扣率和配件收费金额进行赋值
      // this.$set(obj, 'IS_FINISHED', 10041002);
      // this.$set(obj, 'PART_SALES_AMOUNT', obj.SALES_AMOUNT);
      // this.$set(obj, 'DISCOUNT', 1);
      // this.$set(obj, 'IS_DISCOUNT', 10041002);
      // this.$set(obj, 'ITEM_ID', 'N');
      // 插入值
      this.BaseTable.EXECUTE_INSERT(obj);
      // this.salesOrderAddVisible = false;
      this.outStockBtn = true;
      this.buildBtn = true;
      this.saveltBtn = false;
      this.cancelBtn = false;
      this.moveAddVisible = false;
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    showHandler() {
      this.visible = true;
    },
    closeHandler(val, type) {
      this.visible = val;
    },
    afterVisibleChangeHandle(val) {
      if (val == false) {
        this.fetchParams = { ...this.fetchParams };
      }
    },

    // 清空
    delCustomerDealer() {
      this.topFilterList.find(item => item.fieldName == 'transferNo').initialValue = '';
      this.topFilterList.find(item => item.fieldName == 'transferDate').initialValue = '';
      this.topFilterList = [...this.topFilterList];
    },
    // 移库单号赋值
    getCustomerInfo() {},
    // 表格同步数据
    async syncTableFun(val) {
      this.syncTableList = val;
      // console.log('表单数据', 1232133);

      this.dataSource = val;
    },
    async getUnit() {
      const res = await queryUnitCode();
      console.log('getUnit res::', res);
      let data = arrayObjDeWeight(res.data, 'UNIT_CODE');
      this.columns.find(x => x.dataIndex == 'UNIT_CODE').dictItems = data.map(x => ({ value: x.UNIT_CODE + '', text: x.UNIT_NAME }));
    },
    async getSalerList() {
      // this.$refs.table.START_LOADING();
      // this.
      let emps = await getDealerUser();
      let obj = {};
      emps.data.map(item => {
        obj[item.userId] = item.employeeName;
      });
      this.salerList = obj;
    },
    // 查询打印参数
    async queryPrintParams() {
      let res = await dealerPrintApi({
        vModule: '90211009',
        vNormalCode: 'BJDB'
      });
      if (res.resultCode == 200 && res.data.length) {
        this.printParams = res.data[0];
        this.printParams.vDirectPrint = this.printParams.vDirectPrint === 0 ? '0' : this.printParams.vDirectPrin;
      }
      console.log(this.printParams, '打印参数');
    }
  }
};
</script>

<style lang="less" scoped></style>
